const { URLSearchParams } = require('url');
const request = require('request');

function sleep(time = 1) {
    return new Promise(resolve => {
        setTimeout(() => {
            resolve();
        }, time * 1000);
    })
}

function post(url, form = {}, headers = {}) {
    return new Promise(resolve => {
        request({
            url,
            method: 'POST',
            headers,
            form
        }, (error, response, body) => {
            if (error) {
                resolve();
            } else {
                resolve(JSON.parse(body));
            }
        })
    })
}

function get(url, headers = {}) {
    return new Promise(resolve => {
        request({
            url,
            method: 'GET',
            headers
        }, (error, response, body) => {
            if (error) {
                resolve();
            } else {
                resolve(JSON.parse(body));
            }
        })
    })
}

function createParams(obj = {}) {
    const queryArr = Object.keys(obj).map(key => {
        return [key, obj[key]]
    });
    const params = new URLSearchParams(queryArr);

    return params.toString();
}

module.exports = {
    sleep,
    post,
    get,
    createParams
}